import tensorflow as tf


def decode_example(example):
    features = tf.parse_single_example(example, features={
            'image/height': tf.FixedLenFeature((), tf.int64),
            'image/width': tf.FixedLenFeature((), tf.int64),
            'image/filename': tf.FixedLenFeature((), tf.string),
            'image/source_id': tf.FixedLenFeature((), tf.string),
            'image/encoded': tf.FixedLenFeature((), tf.string, default_value=''),
            'image/format': tf.FixedLenFeature((), tf.string, default_value='jpeg'),
            'image/object/bbox/xmin': tf.VarLenFeature(tf.float32),
            'image/object/bbox/xmax': tf.VarLenFeature(tf.float32),
            'image/object/bbox/ymin': tf.VarLenFeature(tf.float32),
            'image/object/bbox/ymax': tf.VarLenFeature(tf.float32),
            'image/object/class/text': tf.VarLenFeature(tf.string),
            'image/object/class/label': tf.VarLenFeature(tf.int64)
        })

    height = tf.cast(features['image/height'], tf.int64)
    width = tf.cast(features['image/width'], tf.int64)
    filename = tf.cast(features['image/filename'], tf.string)
    source_id = tf.cast(features['image/source_id'], tf.string)
    image = tf.decode_raw(features['image/encoded'], tf.uint8)
    img_format = tf.cast(features['image/format'], tf.string)
    xmin = tf.cast(features['image/object/bbox/xmin'], tf.float32)
    xmax = tf.cast(features['image/object/bbox/xmax'], tf.float32)
    ymin = tf.cast(features['image/object/bbox/ymin'], tf.float32)
    ymax = tf.cast(features['image/object/bbox/ymax'], tf.float32)
    text = tf.cast(features['image/object/class/text'], tf.string)
    label = tf.cast(features['image/object/class/label'], tf.int64)

    return image, height, width, filename, xmin, xmax, ymin, ymax, text


def read_and_decode(filename_queue):
    reader = tf.TFRecordReader()
    _, serialized_example = reader.read(filename_queue)

    return decode_example(serialized_example)


def decode_and_verification(tfrecord_path):
    filename_queue = tf.train.string_input_producer([tfrecord_path])
    image_raw, height, width, filename, xmin, xmax, ymin, ymax, text = read_and_decode(filename_queue)
    print(filename_queue.dequeue())

    return image_raw, height, width, filename, xmin, xmax, ymin, ymax, text
